/**
 *
 * @description:
 * @author: junyong.hong
 * @createTime: 2019/2/23
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const { readFile, writeFile } = require('fs')
const { resolve } = require('path')
const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')
const _ = require('lodash')
const Category = mongoose.model('Category')
const Comment = mongoose.model('Comment')
const util = require('util')
const api = require('../api')

const readFileAsync = util.promisify(readFile)
const writeFileFileAsync = util.promisify(writeFile)

// 0、电影Model创建

// 电影详情页面
exports.detail = async (ctx, next) => {
    const _id = ctx.params._id
    const movie = await api.movie.findMovieById( _id )

    await Movie.update({ _id }, { $inc: { pv : 1 }})

    // 评论
    const comments = await Comment.find({
        movie: _id
    }).populate('from', '_id nickname').populate('replies.from replies.to', '_id nickname')

    await ctx.render('pages/detail', {
        title: '电影详情页面',
        movie,
        comments
    })
}

// 1、电影的录入页面
exports.show = async (ctx, next) => {
    const { _id } = ctx.params
    let movie = {}

    if (_id) {
        movie = await api.movie.findMovieById( _id )
    }

    let categories = await api.movie.findCategories()

    await ctx.render('pages/movie_admin', {
        title: '后台分类录入页面',
        movie,
        categories
    })
}

exports.savePoster = async (ctx, next) => {
    const posterData = ctx.request.body.files.uploadPoster
    const filePath = posterData.path
    const fileName = posterData.name

    if (fileName) {
        // 读取这个路径的文件数据
        const data = await readFileAsync(filePath)
        const timestamp = Date.now()
        const type = posterData.type.split('/')[1]
        const poster = timestamp + '.' + type
        const newPath = resolve(__dirname, '../../../', 'public/upload/' + poster)

        await writeFileFileAsync(newPath, data)

        ctx.poster = poster
    }

    await next()
}

// 2、电影的创建持久化
exports.new = async (ctx, next) => {
    // koa会对表单重新组装，所以会放在fields里
    let movieData = ctx.request.body.fields || {}
    let movie

    if (movieData._id) {
        movie = await api.movie.findMovieById( movieData._id )
    }

    // 如果上下文获取到poster
    if (ctx.poster) {
        movieData.poster = ctx.poster
    }

    const categoryId = movieData.categoryId
    const categoryName = movieData.category
    let category

    // 判断是否有这个分类
    if (categoryId) {
        category = await api.movie.findCategoryById(categoryId)
    } else if (categoryName) {
        category = new Category({ name: categoryName })

        await category.save()
    }

    if (movie) {
        movie = _.extend(movie, movieData)
        movie.category = category._id
    } else {
        delete movieData._id
        movieData.category = category._id
        movie = new Movie(movieData)
    }

    category = await api.movie.findCategoryById(category._id)

    if (category) {
        category.movies = category.movies || []
        category.movies.push(movie._id)

        await category.save()
    }

    await movie.save()
    ctx.redirect('/admin/movie/list')
}

// 3、电影的后台列表
exports.list = async (ctx, next) => {
    // populate查询关联分类
    // category为model
    // name需要的字段
    const movies = await api.movie.fondMoviesAndCategory('name')

    await ctx.render('pages/movie_list', {
        title: '电影列表页面',
        movies
    })
}

// 删除电影数据（删除电影同时要把分类下的电影关联关系也删除掉）
exports.del = async (ctx, next) => {
    const id = ctx.query.id

    // 删除电影同时要把分类下的电影关联关系也删除掉
    const cat = await Category.findOne({
        movies: {
            $in: [id]
        }
    })

    if (cat && cat.movies.length) {
        const index = cat.movies.indexOf(id)
        cat.movies.splice(index, 1)

        await cat.save()
    }

    try {
        await Movie.remove({ _id: id })
        ctx.body = { success: true }
    } catch (err) {
        ctx.body = { success: false }
    }
}

// 4、对应的分类路由规则


// 5、对应的分类页面

// 电影搜索功能
exports.search = async (ctx, next) => {
    // q是搜索
    // p分页
    const { cat, q, p } = ctx.query
    const page = parseInt(p, 10) || 0
    const count = 2
    const index = page * count

    // 分类搜索
    if (cat) {
        const categories = await api.movie.searchByCategroy(cat)
        const category = categories[0]
        let movies = category.movies || []
        let results = movies.slice(index, index + count)

        await ctx.render('pages/results', {
            title: '分类搜索结果页面',
            keyword: category.name,
            currentPage: (page + 1),
            query: 'cat=' + cat,
            totalPage: Math.ceil(movies.length / count),
            movies: results
        })
    } else {    // 全局的关键字搜索
        let movies = await api.movie.searchByKeyword(q)
        let results = movies.slice(index, index + count)
        await ctx.render('pages/results', {
            title: '关键字搜索结果页面',
            keyword: q,
            currentPage: (page + 1),
            query: 'q=' + q,
            totalPage: Math.ceil(movies.length / count),
            movies: results
        })
    }
}
